// 目标管理页面脚本

document.addEventListener('DOMContentLoaded', function() {
    // 初始化目标管理页面
    initGoalsPage();
});

// 全局变量
let goals = [];
let currentGoalId = null;
// 添加排序状态跟踪
let sortConfig = {
    column: null,    // 当前排序的列
    direction: 'asc' // 排序方向: 'asc' 或 'desc'
};

// 初始化目标管理页面
function initGoalsPage() {
    // 加载目标数据
    loadGoals();
    
    // 注册视图切换事件
    const tabButtons = document.querySelectorAll('.tab-btn');
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const view = this.getAttribute('data-view');
            switchView(view);
            
            // 切换视图后重新渲染目标
            renderGoals();
        });
    });
    
    // 注册筛选器变更事件
    const categoryFilter = document.getElementById('category-filter');
    const statusFilter = document.getElementById('status-filter');
    
    categoryFilter.addEventListener('change', filterGoals);
    statusFilter.addEventListener('change', filterGoals);
    
    // 注册排序事件
    const sortableHeaders = document.querySelectorAll('th[data-sort]');
    sortableHeaders.forEach(header => {
        header.addEventListener('click', function() {
            const column = this.getAttribute('data-sort');
            
            // 如果点击的是当前排序列，则切换排序方向
            if (sortConfig.column === column) {
                sortConfig.direction = sortConfig.direction === 'asc' ? 'desc' : 'asc';
            } else {
                sortConfig.column = column;
                sortConfig.direction = 'asc';
            }
            
            // 更新排序图标
            updateSortIcons();
            
            // 重新过滤并排序数据
            filterGoals();
        });
    });
    
    // 注册新建目标按钮事件
    const newGoalBtn = document.getElementById('new-goal-btn');
    newGoalBtn.addEventListener('click', openNewGoalModal);
    
    // 注册模态框关闭按钮事件
    const closeModalButtons = document.querySelectorAll('.close-modal');
    closeModalButtons.forEach(button => {
        button.addEventListener('click', closeModals);
    });
    
    // 注册保存目标按钮事件
    const saveGoalBtn = document.getElementById('save-goal-btn');
    saveGoalBtn.addEventListener('click', saveGoal);
    
    // 注册确认删除按钮事件
    const confirmDeleteBtn = document.getElementById('confirm-delete-btn');
    confirmDeleteBtn.addEventListener('click', confirmDeleteGoal);
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target.classList.contains('modal')) {
            closeModals();
        }
    });
}

// 切换视图
function switchView(view) {
    // 更新按钮状态
    const tabButtons = document.querySelectorAll('.tab-btn');
    tabButtons.forEach(button => {
        button.classList.toggle('active', button.getAttribute('data-view') === view);
    });
    
    // 更新视图显示
    const views = document.querySelectorAll('.goals-view');
    views.forEach(viewElement => {
        viewElement.classList.toggle('active', viewElement.id === `${view}-view`);
    });
}

// 加载目标数据
async function loadGoals() {
    try {
        goals = await api('/goals');
        renderGoals();
    } catch (error) {
        console.error('加载目标失败:', error);
        alert('加载目标数据失败，请刷新页面重试');
    }
}

// 渲染目标数据
function renderGoals() {
    // 获取经过筛选的数据
    let filteredData = filterGoalsData();
    
    // 应用排序
    if (sortConfig.column) {
        filteredData = sortGoals(filteredData, sortConfig.column, sortConfig.direction);
    }
    
    // 根据当前视图渲染
    const currentView = document.querySelector('.tab-btn.active').getAttribute('data-view');
    if (currentView === 'list') {
        renderListView(filteredData);
    } else {
        renderKanbanView(filteredData);
    }
    
    // 更新排序图标
    updateSortIcons();
}

// 筛选目标数据
function filterGoalsData() {
    const category = document.getElementById('category-filter').value;
    const status = document.getElementById('status-filter').value;
    
    return goals.filter(goal => {
        // 类别筛选
        if (category && goal.category !== category) {
            return false;
        }
        
        // 状态筛选
        if (status === 'active' && goal.completed) {
            return false;
        }
        if (status === 'completed' && !goal.completed) {
            return false;
        }
        
        return true;
    });
}

// 筛选目标
function filterGoals() {
    // 获取经过筛选的数据
    let filteredData = filterGoalsData();
    
    // 应用排序
    if (sortConfig.column) {
        filteredData = sortGoals(filteredData, sortConfig.column, sortConfig.direction);
    }
    
    // 根据当前视图渲染
    const currentView = document.querySelector('.tab-btn.active').getAttribute('data-view');
    if (currentView === 'list') {
        renderListView(filteredData);
    } else {
        renderKanbanView(filteredData);
    }
}

// 渲染列表视图
function renderListView(filteredGoals) {
    const goalsList = document.getElementById('goals-list');
    goalsList.innerHTML = '';
    
    if (filteredGoals.length === 0) {
        const emptyRow = document.createElement('tr');
        const emptyCell = document.createElement('td');
        emptyCell.colSpan = 7;
        emptyCell.textContent = '暂无目标数据';
        emptyCell.style.textAlign = 'center';
        emptyCell.style.padding = '2rem 0';
        emptyRow.appendChild(emptyCell);
        goalsList.appendChild(emptyRow);
        return;
    }
    
    filteredGoals.forEach(goal => {
        const row = document.createElement('tr');
        
        // 名称
        const nameCell = document.createElement('td');
        nameCell.textContent = goal.name;
        row.appendChild(nameCell);
        
        // 类别
        const categoryCell = document.createElement('td');
        categoryCell.textContent = getCategoryName(goal.category);
        row.appendChild(categoryCell);
        
        // 进度
        const progressCell = document.createElement('td');
        const progress = Math.min(100, Math.round((goal.completed_time / goal.target_time) * 100));
        
        const progressBar = document.createElement('div');
        progressBar.className = 'goal-progress';
        
        const progressFill = document.createElement('div');
        progressFill.className = 'goal-progress-fill';
        progressFill.style.width = `${progress}%`;
        
        progressBar.appendChild(progressFill);
        progressCell.appendChild(progressBar);
        progressCell.appendChild(document.createTextNode(`${progress}%`));
        row.appendChild(progressCell);
        
        // 目标时间
        const timeCell = document.createElement('td');
        timeCell.textContent = `${goal.completed_time} / ${goal.target_time} 分钟`;
        row.appendChild(timeCell);
        
        // 优先级
        const priorityCell = document.createElement('td');
        const priorityBadge = document.createElement('span');
        priorityBadge.className = `priority-badge priority-${goal.priority}`;
        priorityBadge.textContent = getPriorityName(goal.priority);
        priorityCell.appendChild(priorityBadge);
        row.appendChild(priorityCell);
        
        // 截止日期
        const deadlineCell = document.createElement('td');
        deadlineCell.textContent = goal.deadline ? formatDate(goal.deadline) : '无';
        row.appendChild(deadlineCell);
        
        // 操作
        const actionsCell = document.createElement('td');
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'goal-actions';
        
        // 编辑按钮
        const editBtn = document.createElement('button');
        editBtn.className = 'action-btn edit';
        editBtn.textContent = '编辑';
        editBtn.addEventListener('click', () => openEditGoalModal(goal));
        actionsDiv.appendChild(editBtn);
        
        // 删除按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'action-btn delete';
        deleteBtn.textContent = '删除';
        deleteBtn.addEventListener('click', () => openDeleteConfirmModal(goal.id));
        actionsDiv.appendChild(deleteBtn);
        
        // 完成/重新开始按钮
        const completeBtn = document.createElement('button');
        completeBtn.className = 'action-btn complete';
        
        if (goal.completed) {
            completeBtn.textContent = '重新开始';
            completeBtn.addEventListener('click', () => reopenGoal(goal.id));
        } else {
            completeBtn.textContent = '完成';
            completeBtn.addEventListener('click', () => completeGoal(goal.id));
        }
        
        actionsDiv.appendChild(completeBtn);
        actionsCell.appendChild(actionsDiv);
        row.appendChild(actionsCell);
        
        goalsList.appendChild(row);
    });
}

// 渲染看板视图
function renderKanbanView(filteredGoals) {
    const activeGoalsContainer = document.getElementById('active-goals');
    const completedGoalsContainer = document.getElementById('completed-goals');
    
    // 确保两个容器元素存在
    if (!activeGoalsContainer || !completedGoalsContainer) {
        console.error('找不到看板视图容器元素');
        return;
    }
    
    // 清空容器
    activeGoalsContainer.innerHTML = '';
    completedGoalsContainer.innerHTML = '';
    
    // 分离进行中和已完成的目标
    const activeGoals = filteredGoals.filter(goal => !goal.completed);
    const completedGoals = filteredGoals.filter(goal => goal.completed);
    
    console.log('进行中目标:', activeGoals.length, '已完成目标:', completedGoals.length);
    
    // 渲染进行中目标
    if (activeGoals.length === 0) {
        const emptyItem = document.createElement('div');
        emptyItem.className = 'kanban-item';
        emptyItem.textContent = '暂无进行中的目标';
        emptyItem.style.textAlign = 'center';
        emptyItem.style.color = 'var(--text-light)';
        activeGoalsContainer.appendChild(emptyItem);
    } else {
        activeGoals.forEach(goal => {
            const goalCard = createGoalCard(goal);
            activeGoalsContainer.appendChild(goalCard);
        });
    }
    
    // 渲染已完成目标
    if (completedGoals.length === 0) {
        const emptyItem = document.createElement('div');
        emptyItem.className = 'kanban-item';
        emptyItem.textContent = '暂无已完成的目标';
        emptyItem.style.textAlign = 'center';
        emptyItem.style.color = 'var(--text-light)';
        completedGoalsContainer.appendChild(emptyItem);
    } else {
        completedGoals.forEach(goal => {
            const goalCard = createGoalCard(goal);
            completedGoalsContainer.appendChild(goalCard);
        });
    }
}

// 创建目标卡片
function createGoalCard(goal) {
    const card = document.createElement('div');
    card.className = 'kanban-item';
    
    // 卡片头部
    const header = document.createElement('div');
    header.className = 'kanban-item-header';
    
    const title = document.createElement('div');
    title.className = 'kanban-item-title';
    title.textContent = goal.name;
    
    const priorityBadge = document.createElement('span');
    priorityBadge.className = `priority-badge priority-${goal.priority}`;
    priorityBadge.textContent = getPriorityName(goal.priority);
    
    header.appendChild(title);
    header.appendChild(priorityBadge);
    card.appendChild(header);
    
    // 类别
    const category = document.createElement('div');
    category.className = 'kanban-item-category';
    category.textContent = getCategoryName(goal.category);
    card.appendChild(category);
    
    // 进度条
    const progress = Math.min(100, Math.round((goal.completed_time / goal.target_time) * 100));
    
    const progressBar = document.createElement('div');
    progressBar.className = 'goal-progress';
    
    const progressFill = document.createElement('div');
    progressFill.className = 'goal-progress-fill';
    progressFill.style.width = `${progress}%`;
    
    progressBar.appendChild(progressFill);
    
    const progressText = document.createElement('div');
    progressText.textContent = `${progress}% (${goal.completed_time}/${goal.target_time}分钟)`;
    progressText.style.fontSize = '0.8rem';
    progressText.style.marginTop = '0.3rem';
    
    const progressContainer = document.createElement('div');
    progressContainer.appendChild(progressBar);
    progressContainer.appendChild(progressText);
    
    card.appendChild(progressContainer);
    
    // 卡片底部
    const footer = document.createElement('div');
    footer.className = 'kanban-item-footer';
    
    // 截止日期
    if (goal.deadline) {
        const deadline = document.createElement('div');
        deadline.className = 'kanban-item-deadline';
        deadline.textContent = `截止: ${formatDate(goal.deadline)}`;
        footer.appendChild(deadline);
    }
    
    // 操作按钮
    const actions = document.createElement('div');
    actions.className = 'goal-actions';
    
    // 编辑按钮
    const editBtn = document.createElement('button');
    editBtn.className = 'action-btn edit';
    editBtn.textContent = '编辑';
    editBtn.addEventListener('click', () => openEditGoalModal(goal));
    actions.appendChild(editBtn);
    
    // 删除按钮
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'action-btn delete';
    deleteBtn.textContent = '删除';
    deleteBtn.addEventListener('click', () => openDeleteConfirmModal(goal.id));
    actions.appendChild(deleteBtn);
    
    // 完成/重新开始按钮
    const completeBtn = document.createElement('button');
    completeBtn.className = 'action-btn complete';
    
    if (goal.completed) {
        completeBtn.textContent = '重新开始';
        completeBtn.addEventListener('click', () => reopenGoal(goal.id));
    } else {
        completeBtn.textContent = '完成';
        completeBtn.addEventListener('click', () => completeGoal(goal.id));
    }
    
    actions.appendChild(completeBtn);
    footer.appendChild(actions);
    
    card.appendChild(footer);
    
    return card;
}

// 打开新建目标模态框
function openNewGoalModal() {
    currentGoalId = null;
    document.getElementById('modal-title').textContent = '创建新目标';
    document.getElementById('goal-form').reset();
    document.getElementById('goal-id').value = '';
    document.getElementById('goal-target-time').value = 25;
    document.getElementById('goal-modal').style.display = 'block';
}

// 打开编辑目标模态框
function openEditGoalModal(goal) {
    currentGoalId = goal.id;
    document.getElementById('modal-title').textContent = '编辑目标';
    
    // 填充表单
    document.getElementById('goal-id').value = goal.id;
    document.getElementById('goal-name').value = goal.name;
    document.getElementById('goal-description').value = goal.description || '';
    document.getElementById('goal-category').value = goal.category;
    document.getElementById('goal-target-time').value = goal.target_time;
    document.getElementById('goal-priority').value = goal.priority;
    
    if (goal.deadline) {
        // 转换为 YYYY-MM-DD 格式
        const date = new Date(goal.deadline);
        const formattedDate = date.toISOString().split('T')[0];
        document.getElementById('goal-deadline').value = formattedDate;
    } else {
        document.getElementById('goal-deadline').value = '';
    }
    
    document.getElementById('goal-tags').value = Array.isArray(goal.tags) ? goal.tags.join(',') : '';
    
    document.getElementById('goal-modal').style.display = 'block';
}

// 打开删除确认模态框
function openDeleteConfirmModal(goalId) {
    currentGoalId = goalId;
    document.getElementById('confirm-modal').style.display = 'block';
}

// 关闭所有模态框
function closeModals() {
    document.getElementById('goal-modal').style.display = 'none';
    document.getElementById('confirm-modal').style.display = 'none';
}

// 保存目标
async function saveGoal() {
    // 获取表单数据
    const goalId = document.getElementById('goal-id').value;
    const name = document.getElementById('goal-name').value;
    const description = document.getElementById('goal-description').value;
    const category = document.getElementById('goal-category').value;
    const targetTime = parseInt(document.getElementById('goal-target-time').value);
    const priority = document.getElementById('goal-priority').value;
    const deadline = document.getElementById('goal-deadline').value;
    const tagsString = document.getElementById('goal-tags').value;
    
    // 验证必填字段
    if (!name || !targetTime) {
        alert('请填写必填字段');
        return;
    }
    
    // 构建目标数据
    const goalData = {
        name,
        description,
        category,
        target_time: targetTime,
        priority,
        deadline: deadline || null,
        tags: tagsString ? tagsString.split(',').map(tag => tag.trim()) : []
    };
    
    try {
        if (goalId) {
            // 更新现有目标
            await api(`/goals/${goalId}`, 'PUT', goalData);
        } else {
            // 创建新目标
            await api('/goals', 'POST', goalData);
        }
        
        // 关闭模态框
        closeModals();
        
        // 重新加载目标
        await loadGoals();
        
    } catch (error) {
        console.error('保存目标失败:', error);
        alert('保存目标失败，请重试');
    }
}

// 确认删除目标
async function confirmDeleteGoal() {
    if (!currentGoalId) return;
    
    try {
        await api(`/goals/${currentGoalId}`, 'DELETE');
        
        // 关闭模态框
        closeModals();
        
        // 从本地列表中移除
        goals = goals.filter(goal => goal.id !== currentGoalId);
        
        // 重新渲染
        renderGoals();
        
    } catch (error) {
        console.error('删除目标失败:', error);
        alert('删除目标失败，请重试');
    }
}

// 标记目标为完成
async function completeGoal(goalId) {
    const goal = goals.find(g => g.id === goalId);
    if (!goal) return;
    
    try {
        await api(`/goals/${goalId}`, 'PUT', { completed: true });
        
        // 更新本地数据
        goal.completed = true;
        
        // 重新渲染
        renderGoals();
        
    } catch (error) {
        console.error('完成目标失败:', error);
        alert('操作失败，请重试');
    }
}

// 重新开始目标
async function reopenGoal(goalId) {
    const goal = goals.find(g => g.id === goalId);
    if (!goal) return;
    
    try {
        await api(`/goals/${goalId}`, 'PUT', { completed: false });
        
        // 更新本地数据
        goal.completed = false;
        
        // 重新渲染
        renderGoals();
        
    } catch (error) {
        console.error('重新开始目标失败:', error);
        alert('操作失败，请重试');
    }
}

// 获取类别名称
function getCategoryName(category) {
    const categoryMap = {
        'work': '工作',
        'study': '学习',
        'personal': '个人',
        'other': '其他'
    };
    
    return categoryMap[category] || category;
}

// 获取优先级名称
function getPriorityName(priority) {
    const priorityMap = {
        'high': '高',
        'medium': '中',
        'low': '低'
    };
    
    return priorityMap[priority] || priority;
}

// 日期格式化
function formatDate(date) {
    const d = new Date(date);
    return d.toLocaleDateString('zh-CN');
}

// 排序目标数据
function sortGoals(goalsData, column, direction) {
    return [...goalsData].sort((a, b) => {
        let valueA, valueB;
        
        // 根据不同列提取排序值
        switch(column) {
            case 'name':
                valueA = a.name.toLowerCase();
                valueB = b.name.toLowerCase();
                break;
            case 'category':
                valueA = getCategoryName(a.category).toLowerCase();
                valueB = getCategoryName(b.category).toLowerCase();
                break;
            case 'progress':
                valueA = (a.completed_time / a.target_time) * 100;
                valueB = (b.completed_time / b.target_time) * 100;
                break;
            case 'target_time':
                valueA = a.target_time;
                valueB = b.target_time;
                break;
            case 'priority':
                // 优先级排序：high > medium > low
                const priorityOrder = { high: 3, medium: 2, low: 1 };
                valueA = priorityOrder[a.priority] || 0;
                valueB = priorityOrder[b.priority] || 0;
                break;
            case 'deadline':
                // 处理可能为空的截止日期
                valueA = a.deadline ? new Date(a.deadline).getTime() : Number.MAX_SAFE_INTEGER;
                valueB = b.deadline ? new Date(b.deadline).getTime() : Number.MAX_SAFE_INTEGER;
                break;
            default:
                // 默认按ID排序
                valueA = a.id;
                valueB = b.id;
        }
        
        // 排序方向
        if (direction === 'asc') {
            return valueA > valueB ? 1 : valueA < valueB ? -1 : 0;
        } else {
            return valueA < valueB ? 1 : valueA > valueB ? -1 : 0;
        }
    });
}

// 更新排序图标
function updateSortIcons() {
    // 先清除所有排序图标和active类
    document.querySelectorAll('th[data-sort]').forEach(header => {
        header.classList.remove('active');
        const icon = header.querySelector('.sort-icon');
        if (icon) icon.textContent = '↕';
    });
    
    // 设置当前排序列的图标和active类
    if (sortConfig.column) {
        const currentHeader = document.querySelector(`th[data-sort="${sortConfig.column}"]`);
        if (currentHeader) {
            currentHeader.classList.add('active');
            const icon = currentHeader.querySelector('.sort-icon');
            if (icon) icon.textContent = sortConfig.direction === 'asc' ? '↑' : '↓';
        }
    }
} 